package com.xsherl.leetcode.solution;

import com.xsherl.leetcode.base.TreeNode;
import com.xsherl.leetcode.utils.PrintUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class BinaryTreeZigzagLevelOrderTraversal {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        zigzagLevelOrder(root, 0, res);
        return res;
    }

    public void zigzagLevelOrder(TreeNode root, int level, List<List<Integer>> res){
        if (root == null){
            return;
        }
        while (res.size() <= level){
            res.add(new LinkedList<>());
        }
        LinkedList<Integer> list = (LinkedList)res.get(level);
        if (level % 2 == 0){
            list.addLast(root.val);
        } else {
            list.addFirst(root.val);
        }
        zigzagLevelOrder(root.left, level + 1, res);
        zigzagLevelOrder(root.right, level + 1, res);
    }

    public static void main(String[] args) {
        TreeNode root = TreeNode.buildTree(1,2,3,4,null,null,5);
        PrintUtils.println(root);
        List<List<Integer>> lists = new BinaryTreeZigzagLevelOrderTraversal().zigzagLevelOrder(root);
        PrintUtils.println(lists);
    }
}
